package persistencia;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Vector;

public class PoolConnection {
	private Vector <Connection> connections = new Vector<Connection>();
	protected String jdbc;
	protected String servidor;
	protected String usuario;
	protected String password;
	protected int cantCon;
	
	private static PoolConnection pool;
	
	private PoolConnection()
	{
		jdbc = "jdbc:sqlserver://"; 
        servidor = "localhost:1433";
        usuario = "sa";
        password = "1234";
        cantCon = 3;

		for (int i=0; i< cantCon;i++)
			connections.add(connect());
	}
	
	public static PoolConnection getPoolConnection()
	{
		if (pool== null)
			pool =new PoolConnection();
		return pool;
	}
	private Connection connect()
	{
		try
		{
			Class.forName ("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance ();
            String dbConnectString = jdbc + servidor; 
            Connection con = DriverManager.getConnection (dbConnectString, usuario, password);
            
            return con;
		}
		catch (Exception e)
		{
			System.out.println("Error al conectarse");
			return null;
		}
	}
	
	public  Connection getConnection()
	{
		Connection c = null;
		if (connections.size()>0)
			c = connections.remove(0);
		else
		{
			c = connect();
			System.out.println("Se ha creado una nueva conexion fuera de los parametros de configuracion");
		}
		return c;
	}
	public void releaseConnection(Connection c)
	{
		connections.add(c);
	}
}
